package com.epin.config.redis;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.epin.base.plugins.RedisSequence;
import com.epin.business.commons.service.RedisService;
import com.epin.business.commons.service.impl.RedisServiceImpl;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfiguration {
	
	private final static String DEFAULT_CONFIG_FILE = "/redis.properties";

	private static JedisPool pool = null;
	
	
	@Bean
    public RedisSequence redisSeq(){
		RedisSequence redisSeq = new RedisSequence();
		
		return redisSeq;
    }
	
	
	@Bean
	public RedisService redisService(){
		
		RedisServiceImpl redisService = new RedisServiceImpl();
		
		initPool();
		
		redisService.setPool(pool);
		
		return redisService;
	}
	
	
	/**
	 * <p>设置连接池</p>
	 * 
	 * @author fujiajun
	 * @since 2017-09-12
	 */
	private void initPool() {
		if (pool == null || pool.isClosed()) {
			synchronized (RedisConfiguration.class) {
				if (pool == null || pool.isClosed()) {
					try(InputStream in = 
							RedisConfiguration.class.getResourceAsStream(DEFAULT_CONFIG_FILE);){
						
						Properties pro = new Properties();
						pro.load(in);
						
						JedisPoolConfig config = new JedisPoolConfig();
						String host = pro.getProperty("redis.host");
						int port = Integer.valueOf(pro.getProperty("redis.port"));
						int timeout = Integer.valueOf(pro.getProperty("redis.timeout"));
						String password = !StringUtils.isBlank(pro.getProperty("redis.password")) ? pro.getProperty("redis.password") : null;
						int db = Integer.valueOf(pro.getProperty("redis.database"));
						
						pool = new JedisPool(config, host, port, timeout, password, db);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
